<template>
  <div class="padding">
    <el-card class="margin-bottom-sm">
      <div slot="header" class="clearfix">
        <span>发货计划</span>
      </div>
      <el-form
        ref="amazonShipmentPlan"
        :rules="rules"
        size="mini"
        :model="amazonShipmentPlan"
        label-width="120px"
        class="padding-sm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item prop="shopName">
              <div slot="label">店铺</div>
              <el-select
                v-model="amazonShipmentPlan.shopName"
                style="width: 50%"
                filterable
                clearable
                @change="changeShop"
              >
                <el-option
                  v-for="(v, i) in shopNameSource"
                  :key="i"
                  :label="v"
                  :value="v"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="shipFrom">
              <div slot="label">发件人</div>
              <el-select
                v-model="amazonShipmentPlan.shipFrom"
                style="width: 50%"
                filterable
                clearable
              >
                <el-option
                  v-for="(v, i) in shipFromSource"
                  :key="i"
                  :label="shipFromSource[i].name"
                  :value="shipFromSource[i].id"
                />
              </el-select>
              <el-button
                class="margin-left"
                type="primary"
                @click="addShipFrom = true"
              >新增发件人</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="shipToCountryCode">
              <div slot="label">站点</div>
              <el-select
                v-model="amazonShipmentPlan.shipToCountryCode"
                style="width: 50%"
                filterable
                clearable
              >
                <el-option
                  v-for="(v, i) in siteSource"
                  :key="i"
                  :label="v"
                  :value="v"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="sku">
              <div slot="label">SKU</div>
              <el-select
                v-model="amazonShipmentPlan.sku"
                style="width: 50%"
                filterable
                clearable
                remote
                reserve-keyword
                :remote-method="fuzzyQuerySku"
                @change="selectData"
              >
                <el-option
                  v-for="(v, i) in skuSource"
                  :key="i"
                  :label="v.sku"
                  :value="v.sku"
                />
              </el-select>
              <el-button
                class="margin-left"
                type="primary"
                @click="toSKUinfo"
              >SKU管理</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-card v-for="(v, i) in skuData" :key="i" class="margin-top">
          <el-row>
            <el-col :span="8">
              <el-row>
                <el-col :span="6">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="path + v.imgUrl"
                    :preview-src-list="srcList"
                  />
                </el-col>
                <el-col :span="14">
                  <div class="margin-tb">产品SKU：{{ v.sku }}</div>
                  <div class="margin-tb">
                    产品名称(中)：{{ v.declareNameCn }}
                  </div>
                  <div class="margin-tb">
                    产品名称(英)：{{ v.declareNameEn }}
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="6">
              <div class="margin-tb">ASIN：{{ v.asin }}</div>
              <div class="margin-tb flex">
                <span class="margin-top-xs"> 数量：</span>
                <el-input
                  v-model.number="v.quantity"
                  size="mini"
                  style="width: 40%"
                />
              </div>
              <div class="margin-tb flex">
                <span class="margin-top-xs"> 每套个数：</span>
                <el-input
                  v-model.number="v.quantityInCase"
                  size="mini"
                  style="width: 40%"
                />
              </div>
            </el-col>
            <el-col :span="6">
              <div class="margin-tb">FNSKU：{{ v.fnSku }}</div>
            </el-col>
            <el-col :span="4">
              <div class="text-center" style="margin-top: 15%">
                <i class="el-icon-close text-xxl pointer" @click="delList(i)" />
              </div>
            </el-col>
          </el-row>
        </el-card>
        <div class="margin-top-sm">
          <el-button
            size="small"
            type="primary"
            @click="submit('amazonShipmentPlan')"
          >提交发货计划</el-button>
          <span class="margin-top-xs">
            本流程暂时仅支持小包裹补货(暂不支持卡派)</span>
        </div>
      </el-form>
    </el-card>

    <!-- 新增发件人 -->
    <el-dialog title="新增发件人" :visible.sync="addShipFrom" width="40%">
      <el-form
        ref="shipForm"
        :model="shipForm"
        :rules="shipFormRules"
        size="mini"
        label-position="left"
        label-width="140px"
        class="padding-lr-40"
      >
        <el-form-item prop="name">
          <div slot="label">发件人</div>
          <el-input
            v-model="shipForm.name"
            placeholder="请填写发件公司名/或者个人"
          />
        </el-form-item>
        <el-form-item prop="provinces">
          <div slot="label">地址</div>
          <el-cascader
            v-model="shipForm.provinces"
            filterable
            :options="cityOptions"
            placeholder="请选择地址"
            @change="cityHandleChange"
          />
        </el-form-item>
        <!-- <el-form-item prop="stateOrProvinceCode">
          <div slot="label">省</div>
          <el-input
            v-model="shipForm.stateOrProvinceCode"
            placeholder="请填写省/自治区/直辖市"
          />
        </el-form-item>
        <el-form-item prop="city">
          <div slot="label">城市</div>
          <el-input v-model="shipForm.city" placeholder="请填写城市" />
        </el-form-item>
        <el-form-item prop="districtOrCounty">
          <div slot="label">区县</div>
          <el-input
            v-model="shipForm.districtOrCounty"
            placeholder="请填写区县"
          />
        </el-form-item> -->

        <el-form-item prop="addressLine1">
          <div slot="label">地址1</div>
          <el-input
            v-model="shipForm.addressLine1"
            placeholder="请填写地址信息1"
          />
        </el-form-item>
        <el-form-item prop="addressLine2">
          <div slot="label">地址2</div>
          <el-input
            v-model="shipForm.addressLine2"
            placeholder="请填写地址信息2"
          />
        </el-form-item>
        <el-form-item prop="postalCode">
          <div slot="label">邮编</div>
          <el-input v-model="shipForm.postalCode" placeholder="请填写邮编" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="addShipFrom = false">取消</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="validateShipFrom('shipForm')"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { getPcas } from '@/utils/city-pcas.js'
import { getInfo } from '@/api/user'
import {
  initData,
  queryShipFrom,
  createShipFrom,
  fuzzyQuerySku,
  createShipmentPlan
} from '@/api/amazon'
import LogoVue from '@/layout/components/Sidebar/Logo.vue'
import globalData from '@/utils/config'
export default {
  components: {},
  data() {
    return {
      addShipFrom: false,
      path: globalData.fileUrl,
      amazonShipmentPlan: {
        shopName: '', // 店铺名称
        // 发件人信息
        shipFromName: '',
        shipFromAddressLine1: '',
        shipFromAddressLine2: '',
        shipFromDistrictOrCounty: '',
        shipFromCity: '',
        shipFromStateOrProvinceCode: '',
        shipFromCountryCode: '',
        shipFromPostalCode: '',
        // 站点
        shipToCountryCode: '',
        // SKU信息
        items: []
      },
      shipForm: {
        name: '', // 发件人公司名
        provinces: [],
        stateOrProvinceCode: '', // 省份
        city: '', // 城市
        districtOrCounty: '', // 区县
        street: '', // 街道
        addressLine1: '', // 地址1
        addressLine2: '', // 地址2
        postalCode: '', // 邮编
        countryCode: 'CN' // 国家
      },
      cityOptions: getPcas(),
      shopNameSource: [],
      siteSource: [],
      shipFromSource: [],
      skuSource: [],
      skuData: [],
      obj: {},
      mount: '',
      url:
        'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
      srcList: [
        'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
      ],
      rules: {
        shopName: [
          {
            required: true,
            message: '请选择店铺',
            trigger: 'change'
          }
        ],
        shipFrom: [
          {
            required: true,
            message: '请选择发件人',
            trigger: 'change'
          }
        ],
        shipToCountryCode: [
          {
            required: true,
            message: '请选择站点',
            trigger: 'change'
          }
        ],
        sku: [
          {
            required: true,
            message: '请填写sku',
            trigger: 'change'
          }
        ]
      },
      shipFormRules: {
        name: [
          {
            required: true,
            message: '请填写发件人公司名/个人名',
            trigger: 'blur'
          }
        ],
        // stateOrProvinceCode: [
        //   {
        //     required: true,
        //     message: '省/自治州/直辖市',
        //     trigger: 'blur'
        //   }
        // ],
        addressLine1: [
          {
            required: true,
            message: '请填写详细地址',
            trigger: 'blur'
          }
        ],
        // city: [
        //   {
        //     required: true,
        //     message: '请填写城市',
        //     trigger: 'blur'
        //   }
        // ],
        // districtOrCounty: [
        //   {
        //     required: true,
        //     message: '请填写区/县',
        //     trigger: 'blur'
        //   }
        // ],
        provinces: [
          { required: true, message: '请选择地址', trigger: 'change' }
        ],
        postalCode: [
          {
            required: true,
            message: '请填写邮编',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {},
  computed: {
    ...mapGetters(['publicData'])
  },
  mounted() {
    this.init()
    for (const i of this.cityOptions) {
      for (const v of i.children) {
        for (const k of v.children) {
          k.children.push({
            label: '暂不选择',
            value: ''
          })
        }
      }
    }
    // this.queryShipFrom()
  },
  methods: {
    async init() {
      const res = await initData({})
      console.log(res)
      this.shopNameSource = res.data.shopName
      this.obj = res.data.site
      this.shipFromSource = res.data.shipFrom
    },
    async queryShipFrom() {
      const res = await queryShipFrom({})
      console.log(res)
    },
    // sku搜索
    async fuzzyQuerySku(query) {
      const len = query.split(' ').join('').length
      let arr = []
      if (query !== '' && len > 0) {
        const res = await fuzzyQuerySku({ query: query })
        if (res.data && res.data.length > 0) {
          arr = res.data
          this.skuSource = arr
          // for (const i of this.skuSource) {
          //   let index = this.skuSource.indexOf(i.sku)
          //   if (index > -1) {
          //     this.skuSource.splice(index, 1)
          //     this.skuSource = [...new Set(this.skuSource)]
          //   } else {
          //     this.skuSource = [...new Set(this.skuSource)]
          //   }
          // }
          console.log('this.skuSource: ', this.skuSource)
        }
      }
    },
    // 选中的sku
    selectData() {
      for (const i of this.skuSource) {
        if (this.amazonShipmentPlan.sku === i.sku) {
          this.skuData.push({
            sku: i.sku,
            declareNameCn: i.declareNameCn,
            declareNameEn: i.declareNameEn,
            asin: i.salesConnection,
            fnSku: i.fnSku,
            sku: i.sku,
            imgUrl: i.imgUrl
          })
          this.srcList[0] = this.path + i.imgUrl
        }
      }
      const result = []
      const list = {}
      for (let i = 0; i < this.skuData.length; i++) {
        if (!list[this.skuData[i].asin]) {
          result.push(this.skuData[i])
          list[this.skuData[i].asin] = true
        }
      }
      this.skuData = result
    },
    // 删除
    delList(i) {
      this.skuData.splice(i, 1)
    },
    cityHandleChange(val) {
      if (!val) return
      this.shipForm.stateOrProvinceCode = val[0]
      this.shipForm.city = val[1]
      this.shipForm.districtOrCounty = val[2]
      this.shipForm.street = val[3]
    },
    // 跳转sku管理
    toSKUinfo() {
      window.open(`#/myProfile/skuInfo`)
    },
    changeShop() {
      this.siteSource = this.obj[this.amazonShipmentPlan.shopName]
    },
    submit(amazonShipmentPlan) {
      this.$refs[amazonShipmentPlan].validate(valid => {
        if (valid) {
          this.createShipmentPlan()
        } else {
          return false
        }
      })
    },
    // 保存
    async createShipmentPlan() {
      this.amazonShipmentPlan.items = []
      // 请求数据格式
      // {
      //   "shopName": "店铺名称(取店铺值)",
      //   "shipFromName": "发件人公司(根据下拉取name值)",
      //   "shipFromAddressLine1": "发件人地址",
      //   "shipFromAddressLine2": "发件人地址",
      //   "shipFromDistrictOrCounty": "发件人区县",
      //   "shipFromCity": "发件人城市",
      //   "shipFromStateOrProvinceCode": "发件人省",
      //   "shipFromCountryCode": "CN",
      //   "shipFromPostalCode": "发件人邮编",
      //   "shipToCountryCode": "目的国家(取站点值)",
      //   "items": [{
      //     "sellerSKU": "遍历SKU信息取SKU值",
      //     "asin": "遍历SKU信息取ASIN",
      //     "quantity": "遍历SKU信息取quantity",
      //     "quantityInCase": "遍历SKU信息取quantityInCase"
      //   }]
      // }
      for (const i of this.shipFromSource) {
        if (this.amazonShipmentPlan.shipFrom === i.id) {
          this.amazonShipmentPlan.shipFromName = i.name
          this.amazonShipmentPlan.shipFromAddressLine1 = i.addressLine1
          this.amazonShipmentPlan.shipFromAddressLine2 = i.addressLine2
          this.amazonShipmentPlan.shipFromDistrictOrCounty = i.districtOrCounty
          this.amazonShipmentPlan.shipFromCity = i.city
          this.amazonShipmentPlan.shipFromStateOrProvinceCode =
            i.stateOrProvinceCode
          this.amazonShipmentPlan.shipFromCountryCode = i.countryCode
          this.amazonShipmentPlan.shipFromPostalCode = i.postalCode
        }
      }
      for (const c of this.skuData) {
        this.amazonShipmentPlan.items.push({
          sellerSKU: c.sku,
          asin: c.asin,
          quantity: c.quantity,
          quantityInCase: c.quantityInCase
        })
      }
      this.$store.dispatch('app/toggleDialog', true)
      const res = await createShipmentPlan(this.amazonShipmentPlan)
      console.log(res)
      if (res.code === 200) {
        this.$message.success(res.message || '保存成功')
      } else {
        this.$message.error(res.message || '保存失败')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    // 保存发件人并带校验
    validateShipFrom(shipFormData) {
      this.$refs[shipFormData].validate(valid => {
        if (!valid) {
          return false
        }
        this.createShipFrom()
      })
    },
    // 新增发件人
    async createShipFrom() {
      console.log(this.shipForm)
      const res = await createShipFrom(this.shipForm)
      console.log(res)
      if (res.code === 200) {
        this.$message.success(res.message || '保存成功')
        this.init()
      } else {
        this.$message.error(res.message || '保存失败')
      }
    }
  }
}
</script>

<style scoped>
/* /deep/.el-card {
  border: 1px solid #fff;
}
/deep/.el-card.is-always-shadow,
.el-card.is-hover-shadow:focus,
.el-card.is-hover-shadow:hover {
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 0%);
} */
</style>
